package com.anrong.wulansdk.sdk.exception;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import com.anrong.wulansdk.sdk.WLData;
import com.anrong.wulansdk.sdk.utils.Utils;



/**
 * 自定义异常捕获类
 * @author cxy
 *
 */
public class CrashHandler implements UncaughtExceptionHandler{
	
	private static CrashHandler myCrashHandler;
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	private Context context;
	
    private CrashHandler(){  
    }  
  
    public static synchronized CrashHandler getInstance(){
    	if (myCrashHandler == null) {
			myCrashHandler = new CrashHandler();
		}
        return myCrashHandler;  
    }
    
    public void init(Context context){
    	this.context = context;
    	mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    	Thread.setDefaultUncaughtExceptionHandler(this);
    }
  
    public void uncaughtException(Thread thread, Throwable ex){
    	// 在这里捕获异常信息  
//    	String errorInfo = getErrorInfoFromException(ex);
//    	saveFile(ex.getMessage(), "error.txt");

    	if (!handleException(ex) && mDefaultHandler != null) {  
    		//如果用户没有处理则让系统默认的异常处理器来处理  
    		mDefaultHandler.uncaughtException(thread, ex);  
    	} else {  //如果自己处理了异常，则不会弹出错误对话框，则需要手动退出app
    		try {  
    			Thread.sleep(3000);  
    		} catch (InterruptedException e) {  
    		}  
    		android.os.Process.killProcess(android.os.Process.myPid());  
    		System.exit(1);  
    	}
    }
    
    
	public static String getErrorInfoFromException(Throwable e) {  
        try {  
            StringWriter sw = new StringWriter();  
            PrintWriter pw = new PrintWriter(sw);  
            e.printStackTrace(pw);  
            return "\r\n" + sw.toString() + "\r\n";  
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";  
        }  
    }
    
    
    private boolean handleException(Throwable ex) {
    	if (ex == null) {
			return false;
		}
    	StringWriter sw = new StringWriter();
    	ex.printStackTrace(new PrintWriter(sw));
    	String error = sw.toString();
    	
    	//TODO 错误写到文件
    	saveFile(ex.getMessage(), "error.txt");
    	
    	
    	Utils.post(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				Toast.makeText(context, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();  
				Looper.loop();
			}
		});
    	
//    	WLData.getInstance().reportError(Utils.getPackageName(context), error);
    	WLData.onSysException("system", error);
    	
		return true;
	}
    
    
    /**
     * 保存异常信息到文件
     * @param data
     * @param file_name
     */
    public static void saveFile(String data, String file_name) {
        File sdPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "wlsdk");
        if (!sdPath.exists()) {
            sdPath.mkdirs();
        }
        File file = new File(sdPath, file_name);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(data.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
